package com.easy.system.controller;

import com.easy.system.model.BaseBean;
import com.easy.system.service.BaseService;
import com.easy.system.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sunguangzhu
 * Date: 13-7-6
 * Time: 下午12:23
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class BaseController<T extends BaseBean> extends AbstractController<T> {
    /**
     * 跳转到首页的公共方法
     *
     * @param request
     * @return
     */
    @RequestMapping
    public String index(Model model, HttpServletRequest request) {
//        String moduleName=clazz.getSimpleName().replace("Controller","");
        String moduleName = clazz.getSimpleName();
        moduleName = moduleName.substring(0, 1).toLowerCase() + moduleName.substring(1);
        model.addAttribute("moduleName", moduleName);
        return request.getServletPath().replace(".do", "");
    }

    /**
     * 增加或保存的公共方法
     * @return
     */
    @ResponseBody
    @RequestMapping
    protected void saveOrUpdate(HttpServletRequest request,HttpServletResponse response) throws Exception {
        T entity = super.dealFormParams(request);
        MessageDto messageDto = new MessageDto();
        try {
            if (entity.getId() != null) {
                this.baseService.update(entity);
                messageDto.setMessage(MessageDefined.update_success_info);
            } else {
                this.baseService.save(entity);
                messageDto.setMessage(MessageDefined.save_success_info);
            }
        } catch (Exception e) {
            messageDto.setSuccess(false);
            messageDto.setMessage(MessageDefined.sys_error_info);
        }
        writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void delete(Long id, HttpServletResponse response) throws IOException {
        MessageDto messageDto = new MessageDto();
        try {
            this.baseService.delete(clazz, id);
            messageDto.setMessage(MessageDefined.del_success_info);
        } catch (Exception e) {
            messageDto.setSuccess(false);
            messageDto.setMessage(MessageDefined.sys_error_info);
        }
        writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void deleteMore(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ids = request.getParameter("ids");
        MessageDto messageDto = new MessageDto();
        try {
            int count = this.baseService.delete(clazz, ids);
            messageDto.setMessage(MessageDefined.del_success_info);
        } catch (Exception e) {
            e.printStackTrace();
            messageDto.setMessage(MessageDefined.sys_error_info);
            messageDto.setSuccess(false);
        }
        writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void getGridData(HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
        Condition condition = this.getBaseSearchCondtion(request);
        Pagination pagination = RequestVarsUtil.getPagination(request);
        List<T> entitys = this.baseService.find(condition, pagination);
        Long total = this.baseService.getTotal(condition);
        ResultDto<List<T>> resultDto = new ResultDto<List<T>>();
        resultDto.setRows(entitys);
        resultDto.setTotal(total);
        resultDto.setSuccess(true);
        writeToClient(response, resultDto.toString());
    }

    private Condition getBaseSearchCondtion(HttpServletRequest request) throws Exception {
        Condition condition = null;
        try {
            Class controller = Class.forName(controllerClass.getName());
            Method method = controller.getDeclaredMethod("getSearchCondtion", HttpServletRequest.class);
            condition = (Condition) method.invoke(controller.newInstance(), request);
        } catch (Exception e) {
            condition = this.getSearchCondtion(request);
        }
        return condition;
    }

    /**
     * @param request
     * @return
     */
    protected Condition getSearchCondtion(HttpServletRequest request) throws Exception {
        Condition condition = new Condition(clazz.getSimpleName());
        List<Condition> conditions = new ArrayList<Condition>();
        String[] fields = ReflectUtil.getFields(clazz).split(",");
        String type = request.getParameter("type");
        System.out.println(type);
        if (type != null) {
            if (type.equals(Constant.ADVANCE_SEARCH)) {
                for (String field : fields) {
                    //分类型
                    if (request.getParameter(field) != null && !request.getParameter(field).equals("")) {
                        conditions.add(new Condition("and", field, "=", request.getParameter(field)));
                    }
                }
            } else {
                if (request.getParameter("all") != null && !request.getParameter("all").equals("")) {
                    for (String field : fields) {
                        conditions.add(new Condition("or", field, "like", "%" + request.getParameter("all") + "%"));
                    }
                } else {
                    for (String field : fields) {
                        if (request.getParameter(field) != null && !request.getParameter(field).equals("")) {
                            conditions.add(new Condition("and", field, "like", "%" + request.getParameter(field) + "%"));
                        }
                    }
                }
            }
            condition.setChildren(conditions);
        }

        return condition;
    }

    @ResponseBody
    @RequestMapping
    protected void getFields(HttpServletResponse response) throws Exception {
        String fields = ReflectUtil.getFields(clazz);
        writeToClient(response, fields);
    }

}
